package com.gxks.lhs.controller.admin;

import com.gxks.lhs.constants.R;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Api(tags = "图片上传模块")
@Slf4j
@RestController
//@RequestMapping("/upload")
public class ImgUpload {
    @Autowired
    private ServletContext servletContext;

    @Value("${upload.path}")
    private String uploadPath;

    @PostMapping("/upload")
    public R update(MultipartFile file) throws IOException {
        // 将用户提交上来的文件 写入到 指定的路径E:/imgs/secondHand/
//        String uploadPath = "E:/imgs/secondHand/";
//        改成从配置中获取路径

//        String webPath = "http://localhost:8080/img/";
        //获取的文件的原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取 . 出现的最后位置
        int i = originalFilename.indexOf(".");
        // 通过字符截取
        String hz = (originalFilename.substring(i));
        // 原始文件名 【如果两个用户提交同一个名字的文件，会造成覆盖】
        String randomStr = UUID.randomUUID().toString() + hz;
        // 内存中 创建了一个文件对象 —— 指定了改文件的存储位置
        File newFile = new File(uploadPath + File.separator + randomStr);
        //Api的调用 将上传的文件对象，转移至我们创建的文件上
        file.transferTo(newFile);
        return R.success().setData("img" + File.separator + randomStr);
//        return R.success();
    }

    //    获取图片
    @GetMapping("/img/{imgName}")
    public void getImg(@PathVariable String imgName, HttpServletResponse response) throws IOException {
        String path = uploadPath + File.separator + imgName;
        File file = new File(uploadPath + File.separator + imgName);

        if (file.exists()) {
            FileInputStream fis = new FileInputStream(file);
            // 设置响应内容类型
            response.setContentType(servletContext.getMimeType(imgName)); // 根据文件名自动识别MIME类型
            IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
        }
    }
}
